package {
	import flash.display.Sprite;
	import flash.system.Capabilities;
	import flash.system.System;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.utils.getTimer;

	/**
	 * 表示一条水流
	 *
	 * @author cuilichen
	 */
	public class Falling extends Sprite {
		private static const sizes:Array = [8, 9, 10, 12]; //字号集合
		public static var w:int = 12;					   //本类对象的一般宽度
		
		private var _x0:int;	  //初始化时的x的值
		private var speed:Number; //竖直方向上运动的速度
		private var maxY:int;     //竖直方向上运动的终点值

		public function Falling(char_color:Array, chars:String, maxY:int, single:Boolean, _name:String = null){
			this.maxY = maxY;
			if (_name){
				this.name = _name;
			}
			var screenHeight:int = Capabilities.screenResolutionY; //计算机硬件的屏幕高度
			do {
				addChars(char_color, chars, single);
			} while (height < screenHeight && !single);
			speed = 1 + 5 * Math.random();
		}

		/**
		 * 添加一个TextField
		 *
		 * @param        char_color
		 * @param        chars
		 */
		private function addChars(char_color:Array, chars:String, single:Boolean):void {
			var tf:TextField = new TextField();
			tf.autoSize = TextFieldAutoSize.LEFT;
			var ind:int = Math.random() * sizes.length;
			var size:int = sizes[ind];	//随机字号
			
			ind = Math.random() * char_color.length;
			tf.defaultTextFormat = new TextFormat("Courier New", size, char_color[ind]);
			
			var show:String = "";
			var length:int = single ? 1 : 100;   //字符距离
			for (var i:int = 0; i < length; i++){
				var temp:String = chars.charAt(int(Math.random() * chars.length));
				if (i > 0){
					show += "\n";
				}
				show += temp;
			}
			tf.text = show;
			tf.x = 0;
			tf.y = height - 3;
			addChild(tf);
		}

		/**
		 * 销毁本对象
		 */
		public function destroy():void {
			while (numChildren > 0){
				removeChildAt(0);
			}
		}

		/**
		 * 本对象的运动。返回值表示是否运动到终点
		 *
		 * @return
		 */
		public function moving():void {
			if (y <= maxY){
				y += speed;
					//if (name == "0") {
					//trace("dd "+y);
					//}
			} else {
				y = -20 - height;
				initMovtion();
			}
		}

		public function get x0():int {
			return _x0;
		}

		public function set x0(value:int):void {
			_x0 = value;
			initMovtion();
		}

		/**
		 * 初始化运动相关参数
		 */
		private function initMovtion():void {
			x = x0 - 20 + 40 * Math.random();
			speed = 1 + 5 * Math.random();
		}
	}
}